package io.github.leon406.ext

import android.graphics.Color
import android.os.SystemClock
import android.view.View
import me.leon.ui.R

fun Any.toColor() =
    when (this) {
        is String -> Color.parseColor(this)
        is Int -> this
        else -> Color.WHITE
    }

fun throttleClick(wait: Long = 200, block: ((View) -> Unit)): View.OnClickListener {

    return View.OnClickListener { v ->
        val current = SystemClock.uptimeMillis()
        val lastClickTime = (v.getTag(R.id.view_click_timestamp) as? Long) ?: 0
        if (current - lastClickTime > wait) {
            v.setTag(R.id.view_click_timestamp, current)
            block(v)
        }
    }
}

fun debounceClick(wait: Long = 200, block: ((View) -> Unit)): View.OnClickListener {
    return View.OnClickListener { v ->
        val action =
            (v.getTag(R.id.view_click_debounce_action) as? DebounceAction)?.also {
                it.block = block
            }
                ?: DebounceAction(v, block)
        v.removeCallbacks(action)
        v.postDelayed(action, wait)
    }
}

class DebounceAction(val view: View, var block: ((View) -> Unit)) : Runnable {
    init {
        view.setTag(R.id.view_click_debounce_action, this)
    }

    override fun run() {
        if (view.isAttachedToWindow) {
            block(view)
        }
    }
}

fun View.onClick(wait: Long = 200, block: ((View) -> Unit)) {
    setOnClickListener(throttleClick(wait, block))
}

fun View.onDebounceClick(wait: Long = 200, block: ((View) -> Unit)) {
    setOnClickListener(debounceClick(wait, block))
}

fun View.visible(isVisible: Boolean) {
    visibility = if (isVisible) View.VISIBLE else View.INVISIBLE
}

fun View.visibleGone(isVisible: Boolean) {
    visibility = if (isVisible) View.VISIBLE else View.GONE
}
